import Com from '../../base/com'
import pagerTpl from './template.hbs'
import InfoPanel from './infos/infos'
import { On } from '@/psoon/ext/decorators'
import { isType } from '@/psoon/base/utils'
import mmpx from '@/psoon/pub/px2mm'
import './style.scss'

const Sizes = {
  a3: { width: '420mm', height: '296mm'},
  a4: { width: '210mm', height: '296mm'},
  a5: { width: '210mm', height: '147mm'},
  b3: { width: '500mm', height: '352mm'},
  b4: { width: '250mm', height: '352mm'},
  b5: { width: '250mm', height: '175mm'},
  biglabel:{ width: '60mm', height: '30mm'},
  biglabel2:{ width: '60mm', height: '15mm'},
  label:{ width: '50mm', height: '15mm'}
}

class Paper extends Com{
  
  pageSize = Object.assign({}, Sizes.biglabel2)

  elEvents = {
    'click @ .print-btn' : 'printPaper',
    'change @ .paper-tp' : _=>{
      const sel = _.target
      const val = $(sel).val()
      const paperEl = this.getPaperEl()
      if(val === 'setting'){
        const curS = { 
          w: mmpx.getNumber(paperEl.style.width, 'mm'), 
          h: mmpx.getNumber(paperEl.style.height, 'mm')
        }
        this.getEl('.size-setting').style.display = 'inline-block'
        this.getEl('input.width').value = curS.w
        this.getEl('input.height').value = curS.h
        this.setPaperSize({ width: curS.w + 'mm', height: curS.h + 'mm'} )
      }else{
        this.getEl('.size-setting').style.display = 'none'
        this.setPaperSize( $(sel).val() )
      }
    },
    'change @ input.width,input.height': (e)=>{
      this.setPaperSize({
        width: this.getEl('input.width').value + 'mm', 
        height: this.getEl('input.height').value + 'mm'
      })
    }
  }

  _blocks = []

  infosPanel = null

  constructor(){
    super( pagerTpl )
    window.paper = this
  }

  onCreated(){
    document.onkeydown = (e) => {
      // console.log(window.event, 'window.event')
      const key = {
         up: 38,
         down: 40,
         left: 37,
         right: 39
      }
      const active = this.getActiveBlock()
      if(active) if (window.event.keyCode == key.up) {
        active && active.offset({up:-1})
        e.stopPropagation && e.stopPropagation()
        e.preventDefault && e.preventDefault()
      }else if (window.event.keyCode == key.down) {
        active && active.offset({up:1})
        e.stopPropagation && e.stopPropagation()
        e.preventDefault && e.preventDefault()
      }else if (window.event.keyCode == key.left) {
        active && active.offset({left:-1})
        e.stopPropagation && e.stopPropagation()
        e.preventDefault && e.preventDefault()
      }else if (window.event.keyCode == key.right) {
        active && active.offset({left:1})
        e.stopPropagation && e.stopPropagation()
        e.preventDefault && e.preventDefault()
      }
    }
  }

  onRendered(){
    this.setPaperSize( 'biglabel2' )
    this.root?.find('.paper-tp').val('biglabel2')
    this.infosPanel = this.addChildTo(new InfoPanel(), '.infos-panel>.items', 'block-infos')
  }

  getActiveBlock(){
    return this.findByClass('active')
  }

  clearActive(){
    const active = this.getActiveBlock()
    active && active.clearActive()
    this.turnBtnClick(null, false)
  }
  // 从block中读取info，显示在编辑面板
  infosByBlock( block ){
    this.infosPanel.setInfos(block)
  }

  @On('turn-btn-click')
  turnBtnClick(e, flg, block){
    const panel = this.getEl('.infos-panel')
    if( !isType(flg, 'Undefined') ) {
      $(panel)[ flg ? 'addClass' : 'removeClass']('open')
      this.infosByBlock( flg ? block : 'clear' )
      return
    }
    if( $(panel).hasClass('open') ){
      $(panel).removeClass('open')
    }else{
      $(panel).addClass('open')
    }
  }

  @On('active-block-change')
  activeBlockChange( actBlock ){
    this.eachChildren( child => {
      if( child.isBlock ){
        child.clearActive()
      }
    })
    this.turnBtnClick(null, true, actBlock)
  }

  setPaperSize( size ){
    const paper = this.getPaperEl()
    paper.style.width = ''
    paper.style.height = ''
    paper.className = 'ps-paper'
    if( isType(size, 'String') ){
      paper.className = 'ps-paper ' + 'ps-'+ size
      const S = Object.assign({}, Sizes[size] || {})
      paper.style.width = S.width
      paper.style.height = S.height
      this.pageSize = Object.assign({}, S)
    }else if(isType(size, 'Object')){
      paper.style.width = size.width
      paper.style.height = size.height
    }
  }

  inbox( flg = true ){
    const el = this.getPaperEl()
    flg ? $(el).addClass('in-box') : $(el).removeClass('in-box')
  }

  clearInbox(){
    this.root?.find('.ps-paper')?.removeClass('in-box')
  }

  getPaperEl(){
    return this.root?.find('.ps-paper')?.get(0)
  }

  appendBlock( block ){
    const paperEl = this.getPaperEl()
    if( block.root ){
      block.appendTo( this, '.ps-paper')
    }else{
      this.addChild(block, '.ps-paper')
    }
    const bel = block.el;
    const bpos = $(bel).offset();
    const ppos = $(paperEl).offset();
    bel && (bel.style.position = 'absolute');
    bel && (bel.style.top = String(mmpx.getNumber(bpos.top - ppos.top, 'mm') + 'mm') )
    bel && (bel.style.left = String(mmpx.getNumber(bpos.left - ppos.left, 'mm') + 'mm') )
  }

  printPaper(){
    const paper = this.getPaperEl()
    const printEls = $(paper.outerHTML)
    const url = 'http://localhost:19527/print'
    printEls.find('.print-block').each( (i, el) => {
      if(el && el.style){
        el.style.left = mmpx.getNumber( el?.style.left, 'mm') + 'mm'
        el.style.top = mmpx.getNumber( el?.style.top, 'mm') + 'mm'
      }
    })
    
    $.ajax({
      url: url,
      type: 'POST',
      datatype: 'json',
      data: {
        content: printEls.get(0).outerHTML
      },
      success: data => {
        // console.log(data)
        // setTimeout(() => {
        //   dos(start + step)
        // }, 0)
      },
      error: (xhr, status, error) => {
        resolve(false, '打印服务未启动')
      }
    })
  }
}

export default Paper